package org.test.jf.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
public class ServiceUtil {

	public static Document doc = XMLUtil.getXMLInfo("service.xml");
	
	public static Map map = getAllNodes();
	
	public static void getServiceInfo(Object object) {
		Class clazz = object.getClass();
		Field[] fields = clazz.getFields();
		for(Field f : fields) {
			String fieldName = f.getName();
//			UserServlet us = (UserServlet) object;
//			Object obj = map.get(fieldName);
//			us.setUserService((UserServiceImpl) obj);
			
			try {
				Object obj = map.get(fieldName);
				String methodName = "set" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
				Method method = clazz.getDeclaredMethod(methodName, obj.getClass().getInterfaces());
				method.invoke(object, obj);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static Map getAllNodes() {
		HashMap<String, Object> map = new HashMap<String, Object>();
		List<Element> list = doc.selectNodes("service-conf/bean");
		for(Iterator<Element> it = list.iterator(); it.hasNext();) {
			Element e = it.next();
			try {
				map.put(e.attribute("name").getValue(), Class.forName(e.attribute("class").getValue()).newInstance());
			} catch (InstantiationException e1) {
				e1.printStackTrace();
			} catch (IllegalAccessException e1) {
				e1.printStackTrace();
			} catch (ClassNotFoundException e1) {
				e1.printStackTrace();
			}
		} 
		return map;
	}
	
}
